package com.jweb.plugin.mybatis;

import java.io.File;
import java.io.FileInputStream;
import java.util.Set;

import javax.sql.DataSource;

import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jweb.plugin.Iplugin;
import com.jweb.util.ClassUtil;
import com.jweb.util.FormatUtil;

public class MybatisPlugin implements Iplugin {
	private static SqlSessionFactory sqlSessionFactory = null;
	private static Configuration config = null;
	private DataSource dataSource = null;
	private String mapperPackage = "";
	private String mapperxmlPackage = "";
	private Logger log = LoggerFactory.getLogger(MybatisPlugin.class);

	// log.info("[Plugin]==>Mybatis加载完成！"
	public static SqlSessionFactory getSqlSessionFactory() {
		return sqlSessionFactory;
	}

	/**
	 * Mybatis插件配置
	 * 
	 * @param dataSource数据源
	 * @param MapperPackage
	 *            Dao层包名路径
	 */
	public MybatisPlugin(DataSource dataSource, String MapperPackage) {
		this.dataSource = dataSource;
		this.mapperPackage = MapperPackage;
	}

	/**
	 * Mybatis插件配置
	 * 
	 * @param dataSource数据源
	 * @param MapperPackage
	 *            Dao层包名路径
	 * @param MapperxmlPackage
	 *            Mapper.xml的路径，如果在dao层路径下，该参数可不配置
	 */
	public MybatisPlugin(DataSource dataSource, String MapperPackage, String MapperxmlPackage) {
		this.dataSource = dataSource;
		this.mapperPackage = MapperPackage;
		System.setProperty("mapperPackage", System.getProperty("mapperPackage") + ";" + MapperPackage);
		this.mapperxmlPackage = MapperxmlPackage;
		TransactionFactory transactionFactory = new JdbcTransactionFactory();// 定义事务工厂
		Environment environment = new Environment("development", transactionFactory, dataSource);
		config = new Configuration(environment);
	}

	@Override
	public boolean start() {
		// 1.1获取Configuration实例或编写配置文件
		// 获取Configuration实例的样例
		// DataSource dataSource = new PooledDataSource("com.mysql.jdbc.Driver","jdbc:mysql://localhost/mybatis?userUnicode=true&amp;characterEncoding=utf8","admin", "123456");

		// config.setCacheEnabled(true); // 启用缓存
		// config.setLazyLoadingEnabled(false);// 延迟加载
		// config.setAggressiveLazyLoading(false);// 延迟加载
		config.setDefaultStatementTimeout(60);// 数据库响应超时时间
		if (FormatUtil.isEmpty(mapperPackage))
			throw new NullPointerException("mapperPackage not found");
		config.addMappers(mapperPackage);// 1.配置dao层
		MapperLocations(config);// 2.配置Mapper.xml

		// Environment en=new Environment(id, transactionFactory, dataSource) ;
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(config);
		log.info("[Plugin]==>Mybatis加载完成！");
		return true;
	}

	public <T extends Interceptor> void addPluginElement(T interceptor) {
		config.addInterceptor(interceptor);
	}
	private void MapperLocations(Configuration config) {
		try {
			if (FormatUtil.isEmpty(mapperxmlPackage))
				mapperxmlPackage = mapperPackage;
			Set<File> set2 = new ClassUtil<File>().getClasses(mapperxmlPackage, ".xml");
			for (File file : set2) {
				XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(new FileInputStream(file), config, file.toString(), config.getSqlFragments());
				xmlMapperBuilder.parse();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean stop() {
		log.warn("==>关闭：Mybatis");
		sqlSessionFactory = null;
		return true;
	}

}
